package com.contain.gateway.utils;

import cn.hutool.Hutool;
import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONUtil;
import com.contain.common.result.IResultCode;
import com.contain.common.result.Result;
import com.contain.common.result.ResultCode;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;

/**
 * @Auther: tianchao
 * @Date: 2021/7/8 23:29
 * @Description:
 */
public class ResponseUtils {
    public static Mono writeErrorInfo(ServerHttpResponse response, IResultCode resultCode){
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        response.getHeaders().set("Access-Control-Allow-Origin", "*");
        response.getHeaders().set("Cache-Control", "no-cache");
        String body = JSONUtil.toJsonStr(Result.failed(resultCode));
        DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(Charset.forName("UTF-8")));
        return response.writeWith(Mono.just(buffer))
                .doOnError(error -> DataBufferUtils.release(buffer));
    }

    public static void main(String[] args) {
        List<String> strings = Convert.toList(String.class, Arrays.asList("a", "b"));
        System.out.println(strings);
    }
}
